package com.lxb.myforum.service.spec

import java.util.ArrayList

import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.CriteriaQuery
import javax.persistence.criteria.Predicate
import javax.persistence.criteria.Root

import org.apache.commons.lang3.StringUtils
import org.springframework.data.jpa.domain.Specification

import com.lxb.myforum.pojo.Post

class PostSpec(private val post: Post) : Specification<Post> {

    override fun toPredicate(root: Root<Post>, query: CriteriaQuery<*>, cb: CriteriaBuilder): Predicate? {
        val predicates = ArrayList<Predicate>()
        if (post.user != null) {
            predicates.add(cb.equal(root.get<Any>("user"), post.user))
        }
        if (StringUtils.isNotBlank(post.title)) {
            predicates.add(cb.like(root.get("title"), "%" + post.title + "%"))
        }
        if (StringUtils.isNotBlank(post.content)) {
            predicates.add(cb.like(root.get("content"), "%" + post.content + "%"))
        }

        query.where(*predicates.toTypedArray())
        return null
    }

}
